﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Utils.Web;
using Core;
using Utils.ControlToLoad;
using System.Collections.Generic;
using Core.DAL;
using System.Transactions;

namespace xManagerWebApp
{
    public partial class ControlExpenseType : ControlWithDDlAndId
    {
        private const String DDL_FIRST_ELEM = "Select...";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.Bind_ddl_Template();
                this.InstanceId = Guid.NewGuid();
            }
            else
            {
                //tenho que carregar todos os controlos
                using (DataAccessDataContext dc = new DataAccessDataContext())
                {
                    var result = from t in dc.Templates
                                 select t;
                    IEnumerator templates = result.GetEnumerator();
                    while (templates.MoveNext())
                    {
                        String controlName = ((Template)(templates.Current)).MetaEditControl;
                        Control c = Page.LoadControl(this.BuildSelectedControlString(controlName));
                        ((IControlToLoadW)c).Bind(this.InstanceId.Value);
                        this.ph_ControlHolder.Controls.Add(c);
                    }
                }
            }
        }

        private String BuildSelectedControlString(String s)
        {
            return "~\\MetaEditControls\\" + s;
        }

        private void Bind_ddl_Template()
        {
            using (DataAccessLayer dal = new DataAccessLayer())
            {
                this.ddl_Template.DataSource = Template.GetAll(dal);
                this.ddl_Template.DataBind();
                this.ddl_Template.Items.Insert(0, DDL_FIRST_ELEM);
            }
        }

        //aqui só deixo ficar aquele que está selecionado. Se não estiver nenhum selecionado n fica nenhum.
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (string.IsNullOrEmpty(this.SelectedControlName))
            {
                this.ph_ControlHolder.Controls.Clear();
                return;
            }
            //mal feito, devia ser carregado o tipo a partir da string para evitar este LoadControl
            Type t = Page.LoadControl(this.SelectedControlName).GetType();

            //se o controlo não for o selecionado é removido
            IEnumerator phControls = this.ph_ControlHolder.Controls.GetEnumerator();
            List<object> toRemove = new List<object>();
            while (phControls.MoveNext())
            {
                if (t != phControls.Current.GetType())
                    toRemove.Add(phControls.Current);

            }
            foreach (object o in toRemove)
            {
                this.ph_ControlHolder.Controls.Remove((Control)o);
            }
        }

      
        //aqui passa a ser feito save só daquele que está selecionado
        public void Save()
        {
            if (this.ddl_Template.SelectedValue.Equals(DDL_FIRST_ELEM))
                return;

            String name = tb_Name.Text;
            String description = tb_Description.Text;
            bool requiresJust = cb_RequiresJust.Checked;
            String template = ddl_Template.SelectedValue;

            ExpenseType expenseType = new ExpenseType();
            expenseType.Name = name;
            expenseType.Description = description;
            expenseType.RequiresJust = requiresJust;
            expenseType.Type = template;
            expenseType.Id = this.InstanceId.Value;

            if (this.ExpenseChainViewer.SelectedChain != default(Guid))
            {
                expenseType.ChainId = this.ExpenseChainViewer.SelectedChain;
                using (TransactionScope ts = new TransactionScope())
                {
                    using (DataAccessLayer dal = new DataAccessLayer())
                    {
                        expenseType.Save(dal);
                    }

                    if (string.IsNullOrEmpty(this.SelectedControlName))
                        return;

                    Type t = Page.LoadControl(this.SelectedControlName).GetType();
                    IEnumerator phControls = this.ph_ControlHolder.Controls.GetEnumerator();
                    while (phControls.MoveNext())
                    {
                        if (t == phControls.Current.GetType())
                            ((IControlToLoadW)phControls.Current).Save();
                    }
                    ts.Complete();
                }
            }
        }

        protected void ddl_Template_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(this.ddl_Template.SelectedValue.Equals(DDL_FIRST_ELEM))
                return;
            String template = ddl_Template.SelectedValue;

            using (DataAccessLayer dal = new DataAccessLayer())
            {
                Template temp = Template.Get(dal, template);
                this.SelectedControlName = this.BuildSelectedControlString(temp.MetaEditControl);
            }
        }
    }
}